<template>
  <view class="animated fadeIn faster page-bg">
    <view class="tab">
      <view class="mb-1 py-2  grabClass ">
        <scroll-view class="tab-scroll" scroll-x="true" scroll-with-animation :scroll-left="scrollLeft">
          <view class="tab-scroll_box">
            <view v-for="(item,index) in listType" :key="index+'1'"
                  class="tab-scroll_item px-2 py-1 " @click="getType(item.id,index)"
                  :class="{'grabClassActive font32':tabsIndex == item.id}">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="d-flex d-flex-middle mb-2 px-2">
        <view class="searchBox d-flex-item">
          <text class="iconfont icon-icon_sousuo first-child"></text>
          <input class="px-5 rounded30  font26  bg-fff" v-model="order_no" placeholder="搜索订单编号"
                 placeholder-class="colorhold"/>
          <text
              v-if="order_no"
              class="iconfont icon-jiufuqianbaoicon08 clear-icon color444"
              @click="clearSearch"></text>
        </view>
        <view class="px-2 colorfff text-center" style="width: 80rpx;" @click="onSearch">
          搜索
        </view>
      </view>
    </view>


    <!-- 添加下拉刷新容器 -->
    <scroll-view
        class="scroll-area"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="onScrollToLower"
        :scroll-y="true"
    >
      <view class="p-2 grabList">
        <view v-for="(item,inde) in grabList" :key="inde+'c'" class="p-2 bg-fff mb-2 list rounded20">
          <view class="d-flex d-flex-middle">
            <image :src="item.escort_icon" class="mr-2 img "></image>
            <view class="d-flex-item">
              <view class="d-flex d-flex-between d-flex-middle">
                <text class="font-bold font30 text-clamp mb-1 d-flex-4">{{ item.escort_name }}</text>
                <text class="color444 mb-1 d-flex-item text-right">{{ item.escort_type_text }}</text>
              </view>
              <view class="mb-1 d-flex d-flex-between d-flex-middle">
                <text class="colorf00 font32 mr-2">￥{{ item.amount }}元</text>
                <view>
                  <text class="color999 mr-2">{{ mapDdata(item.game_type, grab) }}</text>
                  <text class="color999 mb-1">{{ mapDdata(item.game_login_type, grabLogin) }}</text>
                </view>
              </view>
              <view class="d-flex d-flex-between d-flex-middle">
                <text class="color444">{{ item.created_at }}</text>
              </view>
            </view>
          </view>
          <view class="d-flex d-flex-middle mt-2 bg-eee p-1 d-flex-between">
            <view>
              <text class="font28">订单编号：</text>
              <text>{{ item.order_no }}</text>
            </view>
            <image style="width: 30rpx;height: 30rpx;"
                   src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/strike.png"
                   @click="copypw(item.order_no)">
            </image>
          </view>

          <view class="d-flex d-flex-middle mt-1  p-1 d-flex-between">
            <text class="color999 font24 d-flex-4 text-clamp-two">
              {{ item.remark }}
            </text>
            <!--            :class="{'text-clamp-two':isExpanded != inde}"-->
            <!--              <text class="d-flex-item" @click="toggleExpand(inde)" v-if="item.remark && item.remark.length>100">展开-->
            <!--                <text-->
            <!--                    class="iconfont icon-arrow-bottom-small"></text>-->
            <!--              </text>-->
          </view>

          <view class="d-flex-between d-flex d-flex-middle mt-2">
            <view class="colorf00 font36">
              <text v-if="item.escort_type_id != 9 && item.num" class="font24">连打</text>
              <text v-if="item.escort_type_id != 9 &&item.num">{{ item.num }}</text>
              <text v-if="item.escort_type_id != 9 &&item.num" class="font24">单</text>
            </view>
            <view class="d-flex d-flex-middle d-flex-end  ">
              <view class="time-option rounded30 px-2 py-1 font26">
                {{ item.online_time }}
              </view>
              <view class="ml-4 text-center  bgcolor598dfc colorfff px-4 py-1 rounded30 font26"
                    @click="goUrl('/pages/detail/detail',item)">
                我要抢单
              </view>
            </view>
          </view>

        </view>
      </view>

      <view class="load-more d-flex d-flex-center d-flex-column d-flex-middle py-4"
            v-if="loadingType !== 1 || grabList.length === 0">
        <image v-if="loadingType === 2 && grabList.length === 0"
               src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
               style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
        <text class="empty-text">
          {{
            loadingType === 1 ? '正在加载...' :
                (loadingType === 2 && grabList.length === 0) ? '~ 暂无相关订单 ~' :
                    (loadingType === 2 && grabList.length > 0) ? '没有更多数据了' : ''
          }}
        </text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import {
  fileApi
} from '@/http/fileApi.js';
import {
  mapState
} from "vuex"
import {
  homeApi
} from '@/http/homeApi.js';

export default {
  data() {
    return {
      notices: [],
      search: '',
      categoryList: [],
      grabLogin: [{
        type: 1,
        name: '微信'
      }, {
        type: 2,
        name: 'QQ'
      },
        {
          type: 3,
          name: '其他'
        }
      ],
      grabLoginIndex: '',
      grab: [{
        type: 1,
        name: '端游'
      }, {
        type: 2,
        name: '手游'
      }],
      grabIndex: 0,
      listType: [],
      typeIndex: 0,
      seleIndex: -1,
      categoryIndex: -1,
      grabList: [],
      loadingType: 1,
      page: 1,
      type: '',
      game_type: '',
      game_login_type: '',
      allCategory: [],
      cateIndex: -1,
      isExpanded: -1,
      refreshing: false,
      isLoadingMore: false,
      listType: [],
      scrollLeft: 0,
      tabsIndex: '',
      order_no: ''
    }
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
      real_name: state => state.real_name,
      id_card: state => state.id_card,
    })
  },
  async onShow() {
    this.grabList = []
    this.loadingType = 1
    await this.carryType()
    await this.carryList()
  },
  methods: {
    async carryType() {
      try {
        let res = await homeApi.getCarryType();
        this.listType = [{id: '', name: '全部'}, ...res];


        // 确保有数据后再设置默认选中项
        if (this.listType && this.listType.length > 0) {
          this.tabsIndex = this.listType[0].id;
          this.$nextTick(() => {
            this.getScrollW();
          });
        }
      } catch (error) {
        console.error('获取类型列表失败:', error);
      }
    },
    getScrollW() {
      const query = uni.createSelectorQuery().in(this);
      query.selectAll('.tab-scroll_item').boundingClientRect(data => {
        if (data && data.length > 0) {
          // 计算所有标签的总宽度
          let totalWidth = 0;
          data.forEach(item => {
            totalWidth += item.width + 20; // 20是margin
          });
          this.sWidth = totalWidth;
        }
      }).exec()
    },
    getType(e, index) {
      this.scrollLeft = 0;
      this.tabsIndex = e;

      // 计算需要滚动的距离，使选中的标签居中
      const itemWidth = 120; // 假设每个标签平均宽度
      const containerWidth = uni.getSystemInfoSync().windowWidth; // 减去左右margin
      const targetPosition = index * itemWidth;
      const centerPosition = targetPosition - (containerWidth / 2) + (itemWidth / 2);

      this.scrollLeft = Math.max(0, centerPosition);

      this.grabList = [];
      this.page = 1;
      this.carryList();
    },
    getOrder() {
      uni.showToast({
        title: '抢单成功！'
      })
    },
    mapDdata(e, data) {
      // 添加安全检查
      if (!data) return '';
      let name = ""
      data.map((item) => {
        if (item.type == e) {
          name = item.name
        }
      })
      return name
    },
    onSearch() {
      this.page = 1
      this.grabList = [] // 搜索时清空列表
      this.carryList();
    },
    clearSearch() {
      this.order_no = '';
      this.page = 1;
      this.grabList = [];
      // 清除搜索后自动刷新列表
      this.carryList();
    },
    async carryList(id, isRefresh = false) {
      if (!id) id = ''
      let that = this

      // 设置加载状态
      if (isRefresh) {
        that.loadingType = 1
      }

      try {
        let params = {
          game_type: that.game_type,
          game_login_type: that.game_login_type,
          page: isRefresh ? 1 : that.page,
          game_id: id,
          escort_type_id: that.tabsIndex || '',
          order_no: that.order_no
        }
        let result = await fileApi.getCarryList(params)

        // 添加安全检查
        const data = result && result.data ? result.data : []

        if (isRefresh) {
          that.grabList = data
          that.page = 1 // 重置页码
        } else {
          that.grabList = that.grabList.concat(data)
        }


        // 根据返回数据数量判断是否还有更多数据
        if (data && data.length >= 10) { // 假设每页10条数据
          that.loadingType = 0 // 还可以继续加载
        } else {
          that.loadingType = 2 // 没有更多数据
        }
      } catch (error) {
        that.loadingType = 2
        // 出错时确保列表为空或保持原状态
        if (isRefresh) {
          that.grabList = []
        }
        console.error('加载数据出错:', error)
      }
    },
    // 下拉刷新处理函数
    async onRefresh() {
      this.refreshing = true
      this.page = 1
      await this.carryList('', true)
      this.refreshing = false
    },
    // 上拉加载更多
    async onScrollToLower() {
      // 如果正在加载或没有更多数据，则不处理
      if (this.loadingType !== 0 || this.isLoadingMore) {
        return
      }

      this.isLoadingMore = true
      this.page++
      await this.carryList('', false)
      this.isLoadingMore = false
    },
    toggleExpand(e) {
      if (this.isExpanded == e) {
        this.isExpanded = -1
      } else {
        this.isExpanded = e
      }
    },
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        if (data) {
          uni.navigateTo({
            url: `${urlPages}?data=${encodeURIComponent(JSON.stringify(data))}`
          })
        } else {
          uni.navigateTo({
            url: urlPages
          })
        }
      }
    },
    copypw(item) {
      uni.setClipboardData({
        data: `${item}`,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'none'
          })
        }
      })
    },
  }
}
</script>

<style scoped>


.bgcolor598dfc {
  background-color: #464646;
}


.grabClass view:last-child {
  border-right: 2rpx solid transparent;
}

.grabClass view {
  border-right: 2rpx solid #6f6f6f;
}


.grabList .img {
  width: 160rpx;
  height: 160rpx;
}

.d-flex-2 {
  flex: 3;
}

.d-flex-4 {
  flex: 3;
}

.scroll-area {
  height: 100vh;
  padding-top: 190rpx;
}

.cate-on .cate-img {
  border: solid 2px #598dfc;
}


.empty-text {
  color: #999;
  font-size: 28rpx;
}


.tab-scroll {
  flex: 1;
  overflow: hidden;
  box-sizing: border-box;
}

.time-option {
  background-color: #f5f5f5;
}

.tab-scroll_box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  box-sizing: border-box;
}

.tab-scroll_item {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  color: #fff3f3;
}


.color7 {
  color: #0df297;
}

.grabClassActive {
  color: #0df297;
  font-weight: bold;
  text-decoration: underline;
  text-shadow: 0 0 4rpx rgba(79, 81, 81, 0.6),
  0 0 8rpx rgba(49, 51, 50, 0.4);
}

.tab {
  position: fixed;
  z-index: 9999;
  background: #2f2f2f;
  width: 100%;
}

.searchBox {
  position: relative;
  width: 100%;
}

.searchBox input {
  height: 56rpx;
  line-height: 56rpx;
}

.searchBox .first-child {
  position: absolute;
  left: 13rpx;
  top: 12rpx;
}


.clear-icon {
  position: absolute;
  right: 13rpx !important;
  top: 12rpx;
  z-index: 999;
}

</style>
